//
//  HistoryProblemDetailViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-7-15.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "HistoryProblemDetailViewController.h"
#import "CommonDatePickerViewController.h"

@interface HistoryProblemDetailViewController () <UIActionSheetDelegate,CommonDatePickerDelegate>

@property (weak, nonatomic) IBOutlet UIView *topContentView;
@property (weak, nonatomic) IBOutlet UILabel *merchantNameLbl;
@property (weak, nonatomic) IBOutlet UILabel *merchantCodeLbl;
@property (weak, nonatomic) IBOutlet UIButton *endDateBtn;
@property (weak, nonatomic) IBOutlet UITextView *problemTv;

@property (nonatomic, strong) NSDate *date;

- (IBAction)showEndDataAction:(id)sender;

@end

@implementation HistoryProblemDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.problemTv setInputAccessoryView:self.keyboardBar];
    
    self.networkManager = [[NetworkManager alloc] init];
    
    [self initHUD];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    self.title = @"问题详情";
    self.showLeftBtn = YES;
    self.showRightBtn = self.showRightItem;
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_n.png"] forState:UIControlStateNormal];
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_p.png"] forState:UIControlStateHighlighted];
    
    [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_确认_n.png"] forState:UIControlStateNormal];
    [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_确认_p.png"] forState:UIControlStateHighlighted];
    
    [self updateViewWithData];
    
}

- (void)leftNavItemAction:(id)sender {
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)rightNavItemAction:(id)sender {
    [self showSubmitMenuAction];
}

- (void)showSubmitMenuAction {
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@""
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"提交",@"临时提交", nil];
    [sheet showInView:self.view];
}

- (void)updateViewWithData {
    NSDictionary *data = self.problemInfo;
    
    NSString *name = [data objectForKeyOrNil:@"jxsmc"];
    NSString *code = [data objectForKeyOrNil:@"jxsdm"];
    NSString *description = [data objectForKeyOrNil:@"wtms"];
    NSString *endtime = [data objectForKeyOrNil:@"sjz"];
    if ([endtime isKindOfClass:[NSNull class]] || [endtime length] == 0) {
        endtime = @"截止时间";
    }
    
    self.merchantNameLbl.text = name;
    self.merchantCodeLbl.text = code;
    self.problemTv.text = description;
    self.problemTv.editable = NO;
    
    [self.endDateBtn setTitle:endtime forState:UIControlStateNormal];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)dismissKeyBoard {
    [self.problemTv resignFirstResponder];
}

- (IBAction)showEndDataAction:(id)sender {
    if (self.canEditTime) {
        CommonDatePickerViewController *datePicker = (CommonDatePickerViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"CommonDatePicker"];
        datePicker.view.frame = self.view.bounds;
        datePicker.delegate =self;
        [self addChildViewController:datePicker];
        [self.view addSubview:datePicker.view];
    }
}

#pragma mark - CommonDatePickerDelegate
- (void)picker:(CommonDatePickerViewController *)picker didSelectedDate:(NSDate *)date {
    self.date = date;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strDate = [formatter stringFromDate:date];
    
    [self.endDateBtn setTitle:strDate forState:UIControlStateNormal];
    
    [self submitEndTimeUpdate:strDate];
}

//更新截止时间
- (void)submitEndTimeUpdate:(NSString *)updateToDate {
    NSString *problemId = [self.problemInfo objectForKeyOrNil:@"id"];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           problemId,@"id",
                           updateToDate,@"sjz", nil];
    
    [self.networkManager requestWithMethod:modifyTimeOut parameter:param delegate:self];
    
    [self.HUD show:YES];
}

//提交问题
- (void)submitProblem {
    NSString *problemId = [self.problemInfo objectForKeyOrNil:@"id"];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           problemId,@"id", nil];
    
    [self.networkManager requestWithMethod:submitQuestion parameter:param delegate:self];
    
    [self.HUD show:YES];
}

//临时提交
- (void)temporarySubmitProblem {
    NSString *problemId = [self.problemInfo objectForKeyOrNil:@"id"];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           problemId,@"id", nil];
    
    [self.networkManager requestWithMethod:temporarySubmit parameter:param delegate:self];
    
    [self.HUD show:YES];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex != actionSheet.cancelButtonIndex) {
        if (buttonIndex == 0) { //提交
            [self submitProblem];
        } else if (buttonIndex == 1) { //临时提交
            [self temporarySubmitProblem];
        }
    }
}

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    
    if ([data isKindOfClass:[NSDictionary class]]) {
        int code = [[data objectForKeyOrNil:@"code"] integerValue];
        if (code == 0) { //请求成功
            if ([data count] > 0) {
                id dataObject = [data objectForKeyOrNil:@"data"];
                if ([dataObject isKindOfClass:[NSDictionary class]]) {
                    NSInteger resultCode = [[dataObject objectForKeyOrNil:@"result"] integerValue];
                    NSString *msg = @"";
                    
                    if (methodId == modifyTimeOut) {
                        if (resultCode > 0) {
                            msg = @"截止时间修改成功";
                        } else {
                            msg = @"截止时间修改失败";
                        }
                    } else if (methodId == submitQuestion) {
                        if (resultCode > 0) {
                            msg = @"提交成功";
                        } else {
                            msg = @"提交失败";
                        }
                    } else if (methodId == temporarySubmit) {
                        if (resultCode > 0) {
                            msg = @"临时提交成功";
                        } else {
                            msg = @"临时提交失败";
                        }
                    }
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                    message:msg
                                                                   delegate:self
                                                          cancelButtonTitle:@"确定"
                                                          otherButtonTitles:nil];
                    if (methodId == modifyTimeOut) {
                        alert.tag = 1000;
                    } else if (methodId == submitQuestion) {
                        alert.tag = 1001;
                    } else if (methodId == temporarySubmit) {
                        alert.tag = 1002;
                    }
                    
                    [alert show];
                }
            }
        }
        
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    
    [self.HUD hide:YES];
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    if ([msg isKindOfClass:[NSNull class]] || [msg length] == 0) {
        
        if (methodId == modifyTimeOut) {
            msg = @"截止时间修改失败";
        } else if (methodId == submitQuestion) {
            msg = @"提交失败";
        } else if (methodId == temporarySubmit) {
            msg = @"临时提交失败";
        }
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 1001 || alertView.tag == 1002) {
        [self performSelector:@selector(leftNavItemAction:) withObject:nil afterDelay:0.1];
    }
}


@end
